import React, { useState, useCallback } from "react";
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  Space,
  Table,
  Tag,
  Modal,
  message,
  Row,
  Col,
  Radio,
  InputNumber,
  Divider,
  Typography,
  Tooltip,
  Progress,
} from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  CopyOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  FileTextOutlined,
} from "@ant-design/icons";
import styled from "styled-components";
import TemplateForm from "./components/TemplateForm";
import ExamPreview from "./components/ExamPreview";
import type {
  Question,
  QuestionType,
  DifficultyLevel,
  ExamTemplate,
} from "./types";

const { TextArea } = Input;
const { Option } = Select;
const { Title, Text } = Typography;
const { confirm } = Modal;

interface FormValues
  extends Omit<Question, "id" | "createTime" | "updateTime"> {}

const StyledCard = styled(Card)`
  margin-bottom: 24px;
  .ant-card-head-title {
    font-weight: bold;
  }
`;

const DifficultyTag = styled(Tag)<{ $difficulty: DifficultyLevel }>`
  &.ant-tag-green {
    background-color: #f6ffed;
  }
  &.ant-tag-orange {
    background-color: #fff7e6;
  }
  &.ant-tag-red {
    background-color: #fff1f0;
  }
`;

const TypeTag = styled(Tag)<{ $type: QuestionType }>`
  &.ant-tag-blue {
    background-color: #e6f7ff;
  }
  &.ant-tag-purple {
    background-color: #f9f0ff;
  }
  &.ant-tag-cyan {
    background-color: #e6fffb;
  }
`;

const ExamGeneration: React.FC = () => {
  // 状态管理
  const [questions, setQuestions] = useState<Question[]>([
    {
      id: "1",
      type: "choice",
      difficulty: "medium",
      score: 10,
      content:
        "以下哪个不是嵌入式系统的特点？\nA. 实时性\nB. 可靠性\nC. 图形界面\nD. 资源受限",
      answer: "C",
      knowledge: ["嵌入式基础"],
      options: ["实时性", "可靠性", "图形界面", "资源受限"],
      analysis:
        "嵌入式系统的主要特点包括实时性、可靠性、资源受限等，而图形界面不是必需的特点。",
      createTime: "2024-03-15",
      updateTime: "2024-03-15",
    },
    {
      id: "2",
      type: "programming",
      difficulty: "hard",
      score: 20,
      content: "请实现一个基于优先级的任务调度算法",
      answer: "// 示例答案\nclass TaskScheduler {\n  // 实现代码\n}",
      knowledge: ["操作系统", "任务调度"],
      analysis: "任务调度算法需要考虑优先级、时间片分配、上下文切换等因素。",
      tags: ["算法", "系统设计"],
      createTime: "2024-03-15",
      updateTime: "2024-03-15",
    },
  ]);

  const [templates, setTemplates] = useState<ExamTemplate[]>([
    {
      id: "1",
      name: "期中考试模板",
      totalScore: 100,
      duration: 120,
      questionDistribution: {
        choice: {
          count: 20,
          score: 2,
          difficulty: ["easy", "medium"],
        },
        programming: {
          count: 2,
          score: 20,
          difficulty: ["medium", "hard"],
        },
        analysis: {
          count: 2,
          score: 10,
          difficulty: ["medium"],
        },
      },
    },
  ]);

  const [selectedQuestion, setSelectedQuestion] = useState<string | null>(null);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isTemplateModalVisible, setIsTemplateModalVisible] = useState(false);
  const [isGenerating, setIsGenerating] = useState(false);
  const [form] = Form.useForm<FormValues>();
  const [templateForm] = Form.useForm();
  const [selectedTemplate, setSelectedTemplate] = useState<string | null>(null);
  const [isPreviewVisible, setIsPreviewVisible] = useState(false);
  const [examData, setExamData] = useState<{
    templateName: string;
    totalScore: number;
    duration: number;
    questions: Question[];
  } | null>(null);

  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      const now = new Date().toISOString().split("T")[0];

      if (selectedQuestion) {
        // 编辑现有题目
        setQuestions(
          questions.map((q) =>
            q.id === selectedQuestion
              ? {
                  ...values,
                  id: selectedQuestion,
                  createTime: q.createTime,
                  updateTime: now,
                }
              : q
          )
        );
        message.success("题目更新成功！");
      } else {
        // 添加新题目
        const newQuestion: Question = {
          ...values,
          id: Date.now().toString(),
          createTime: now,
          updateTime: now,
        };
        setQuestions([...questions, newQuestion]);
        message.success("题目添加成功！");
      }
      setIsModalVisible(false);
      form.resetFields();
      setSelectedQuestion(null);
    } catch (error) {
      console.error("Validation failed:", error);
    }
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
    setSelectedQuestion(null);
  };

  const handleEdit = (record: Question) => {
    setSelectedQuestion(record.id);
    form.setFieldsValue(record);
    setIsModalVisible(true);
  };

  const handleDelete = (id: string) => {
    confirm({
      title: "确认删除",
      content: "确定要删除这道题目吗？",
      onOk() {
        setQuestions(questions.filter((q) => q.id !== id));
        message.success("删除成功");
      },
    });
  };

  // 处理试卷模板保存
  const handleTemplateSubmit = async () => {
    try {
      const values = await templateForm.validateFields();
      const newTemplate: ExamTemplate = {
        id: selectedTemplate || Date.now().toString(),
        ...values,
      };

      if (selectedTemplate) {
        setTemplates(
          templates.map((t) => (t.id === selectedTemplate ? newTemplate : t))
        );
        message.success("模板更新成功！");
      } else {
        setTemplates([...templates, newTemplate]);
        message.success("模板创建成功！");
      }
      setIsTemplateModalVisible(false);
      templateForm.resetFields();
      setSelectedTemplate(null);
    } catch (error) {
      console.error("Save template failed:", error);
    }
  };

  // 处理试卷生成
  const handleGenerateExam = () => {
    setIsGenerating(true);
    // 模拟试卷生成过程
    setTimeout(() => {
      const selectedTemplate = templates[0]; // 这里应该让用户选择模板
      if (!selectedTemplate) {
        message.error("请先创建试卷模板！");
        setIsGenerating(false);
        return;
      }

      // 根据模板要求筛选题目
      const examQuestions: { [key in QuestionType]: Question[] } = {
        choice: [],
        programming: [],
        analysis: [],
      };

      // 为每种题型选择符合要求的题目
      Object.entries(selectedTemplate.questionDistribution).forEach(
        ([type, config]) => {
          const typeQuestions = questions.filter(
            (q) =>
              q.type === (type as QuestionType) &&
              config.difficulty.includes(q.difficulty)
          );

          // 随机选择指定数量的题目
          const selectedQuestions = typeQuestions
            .sort(() => Math.random() - 0.5)
            .slice(0, config.count);

          examQuestions[type as QuestionType] = selectedQuestions;
        }
      );

      // 生成试卷预览数据
      const newExamData = {
        templateName: selectedTemplate.name,
        totalScore: selectedTemplate.totalScore,
        duration: selectedTemplate.duration,
        questions: Object.values(examQuestions).flat(),
      };

      setExamData(newExamData);
      setIsPreviewVisible(true);
      setIsGenerating(false);
      message.success("试卷生成成功！");
    }, 2000);
  };

  // 复制题目时添加时间戳
  const handleCopyQuestion = (record: Question) => {
    const now = new Date().toISOString().split("T")[0];
    const newQuestion: Question = {
      ...record,
      id: Date.now().toString(),
      content: `${record.content} (复制)`,
      createTime: now,
      updateTime: now,
    };
    setQuestions([...questions, newQuestion]);
    message.success("复制成功！");
  };

  // 题目列表列定义
  const columns = [
    {
      title: "题目类型",
      dataIndex: "type",
      key: "type",
      render: (type: QuestionType) => {
        const typeMap = {
          choice: { color: "blue", text: "选择题" },
          programming: { color: "purple", text: "编程题" },
          analysis: { color: "cyan", text: "分析题" },
        };
        return (
          <TypeTag color={typeMap[type].color} $type={type}>
            {typeMap[type].text}
          </TypeTag>
        );
      },
    },
    {
      title: "难度",
      dataIndex: "difficulty",
      key: "difficulty",
      render: (difficulty: DifficultyLevel) => {
        const difficultyMap = {
          easy: { color: "green", text: "简单" },
          medium: { color: "orange", text: "中等" },
          hard: { color: "red", text: "困难" },
        };
        return (
          <DifficultyTag
            color={difficultyMap[difficulty].color}
            $difficulty={difficulty}
          >
            {difficultyMap[difficulty].text}
          </DifficultyTag>
        );
      },
    },
    {
      title: "分值",
      dataIndex: "score",
      key: "score",
    },
    {
      title: "题目内容",
      dataIndex: "content",
      key: "content",
      ellipsis: true,
      render: (content: string) => (
        <Tooltip title={content}>
          <Text ellipsis style={{ maxWidth: 300 }}>
            {content}
          </Text>
        </Tooltip>
      ),
    },
    {
      title: "知识点",
      dataIndex: "knowledge",
      key: "knowledge",
      render: (knowledge: string[]) => (
        <Space size={[0, 4]} wrap>
          {knowledge.map((item) => (
            <Tag key={item} color="blue">
              {item}
            </Tag>
          ))}
        </Space>
      ),
    },
    {
      title: "更新时间",
      dataIndex: "updateTime",
      key: "updateTime",
    },
    {
      title: "操作",
      key: "action",
      render: (_: any, record: Question) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => {
              setSelectedQuestion(record.id);
              form.setFieldsValue(record);
              setIsModalVisible(true);
            }}
          >
            编辑
          </Button>
          <Button
            type="link"
            icon={<CopyOutlined />}
            onClick={() => handleCopyQuestion(record)}
          >
            复制
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 题目表单
  const questionForm = (
    <Form form={form} layout="vertical">
      <Row gutter={16}>
        <Col span={8}>
          <Form.Item
            name="type"
            label="题目类型"
            rules={[{ required: true, message: "请选择题目类型" }]}
          >
            <Select>
              <Option value="choice">选择题</Option>
              <Option value="programming">编程题</Option>
              <Option value="analysis">分析题</Option>
            </Select>
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item
            name="difficulty"
            label="难度"
            rules={[{ required: true, message: "请选择难度" }]}
          >
            <Select>
              <Option value="easy">简单</Option>
              <Option value="medium">中等</Option>
              <Option value="hard">困难</Option>
            </Select>
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item
            name="score"
            label="分值"
            rules={[{ required: true, message: "请输入分值" }]}
          >
            <InputNumber min={1} max={100} style={{ width: "100%" }} />
          </Form.Item>
        </Col>
      </Row>

      <Form.Item
        name="content"
        label="题目内容"
        rules={[{ required: true, message: "请输入题目内容" }]}
      >
        <TextArea rows={4} placeholder="请输入题目内容" />
      </Form.Item>

      <Form.Item
        name="answer"
        label="参考答案"
        rules={[{ required: true, message: "请输入参考答案" }]}
      >
        <TextArea rows={4} placeholder="请输入参考答案" />
      </Form.Item>

      <Form.Item name="analysis" label="解析">
        <TextArea rows={3} placeholder="请输入题目解析" />
      </Form.Item>

      <Form.Item
        name="knowledge"
        label="知识点"
        rules={[{ required: true, message: "请输入知识点" }]}
      >
        <Select mode="tags" placeholder="请输入知识点">
          <Option value="嵌入式基础">嵌入式基础</Option>
          <Option value="操作系统">操作系统</Option>
          <Option value="数据结构">数据结构</Option>
          <Option value="算法">算法</Option>
        </Select>
      </Form.Item>

      <Form.Item name="tags" label="标签">
        <Select mode="tags" placeholder="请输入标签">
          <Option value="重点">重点</Option>
          <Option value="难点">难点</Option>
          <Option value="综合">综合</Option>
        </Select>
      </Form.Item>

      {form.getFieldValue("type") === "choice" && (
        <Form.Item
          name="options"
          label="选项"
          rules={[{ required: true, message: "请输入选项" }]}
        >
          <Select mode="tags" placeholder="请输入选项，每行一个">
            <Option value="A">选项A</Option>
            <Option value="B">选项B</Option>
            <Option value="C">选项C</Option>
            <Option value="D">选项D</Option>
          </Select>
        </Form.Item>
      )}
    </Form>
  );

  return (
    <div>
      <StyledCard
        title="题库管理"
        extra={
          <Space>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => {
                setSelectedQuestion(null);
                form.resetFields();
                setIsModalVisible(true);
              }}
            >
              添加题目
            </Button>
            <Button
              type="primary"
              icon={<CheckCircleOutlined />}
              onClick={() => {
                setSelectedTemplate(null);
                setIsTemplateModalVisible(true);
              }}
            >
              创建试卷模板
            </Button>
            <Button
              type="primary"
              icon={<FileTextOutlined />}
              onClick={handleGenerateExam}
              loading={isGenerating}
            >
              生成试卷
            </Button>
          </Space>
        }
      >
        <Table
          columns={columns}
          dataSource={questions}
          rowKey="id"
          pagination={{
            defaultPageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
          }}
        />
      </StyledCard>

      {/* 题目编辑模态框 */}
      <Modal
        title={selectedQuestion ? "编辑题目" : "添加题目"}
        open={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        width={800}
      >
        {questionForm}
      </Modal>

      {/* 试卷模板模态框 */}
      <Modal
        title={selectedTemplate ? "编辑试卷模板" : "创建试卷模板"}
        open={isTemplateModalVisible}
        onOk={handleTemplateSubmit}
        onCancel={() => {
          setIsTemplateModalVisible(false);
          templateForm.resetFields();
          setSelectedTemplate(null);
        }}
        width={800}
      >
        <TemplateForm form={templateForm} />
      </Modal>

      {/* 试卷预览模态框 */}
      <Modal
        title="试卷预览"
        open={isPreviewVisible}
        onCancel={() => setIsPreviewVisible(false)}
        width={1000}
        footer={[
          <Button key="back" onClick={() => setIsPreviewVisible(false)}>
            关闭
          </Button>,
          <Button
            key="download"
            type="primary"
            icon={<FileTextOutlined />}
            onClick={() => {
              message.success("试卷已导出！");
              setIsPreviewVisible(false);
            }}
          >
            导出试卷
          </Button>,
        ]}
      >
        {examData && <ExamPreview examData={examData} />}
      </Modal>
    </div>
  );
};

export default ExamGeneration;
